package nju.bishe.weibo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import nju.bishe.weibo.data.OAuthConstant;
import nju.bishe.weibo.data.UserToken;
import nju.bishe.weibo.data.db.UserTokenTable;
import nju.bishe.weibo.helper.Preferences;
import nju.bishe.weibo.helper.Utils;
import weibo4andriod.User;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import weibo4andriod.http.AccessToken;
import weibo4andriod.http.RequestToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;

public class OAuthActivity extends Activity {

	private UserTokenTable dbHelper;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timeline);
		Uri uri = this.getIntent().getData();
		try {
			final UserToken user = getIntent().getParcelableExtra(
					"existingUser");
			final AccessToken accessToken;
			if (user != null) {
				accessToken = new AccessToken(user.getToken(), user.getSecret());
				OAuthConstant.getInstance().setAccessToken(accessToken);
				TwitterApplication.mApi = OAuthConstant.getInstance()
						.getWeibo();
				TwitterApplication.mApi.setToken(user.getToken(),
						user.getSecret());
				TwitterApplication.mApi.setUserId(user.getUser_id());
				TwitterApplication.mPref = PreferenceManager
						.getDefaultSharedPreferences(this);
				SharedPreferences.Editor editor = TwitterApplication.mPref
						.edit();

				editor.putString(Preferences.USERNAME_KEY, user.getUserName());
				editor.putString(Preferences.ACCESSTOKEN, user.getToken());
				editor.putString(Preferences.ACCESSTOKEN_SECRET,
						user.getSecret());
				editor.putString(Preferences.CURRENT_USER_ID, user.getUser_id());
				editor.putLong(Preferences.LAST_DM_REFRESH_KEY,
						Utils.getNowTime());
				editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
						Utils.getNowTime());
				editor.commit();
			} else {
				RequestToken requestToken = OAuthConstant.getInstance()
						.getRequestToken();
				accessToken = requestToken.getAccessToken(uri
						.getQueryParameter("oauth_verifier"));
				final String user_id = accessToken.getParameter("user_id");
				OAuthConstant.getInstance().setAccessToken(accessToken);

			
				saveUserWrapperToDB(accessToken, user_id);
				
				TwitterApplication.mApi = OAuthConstant.getInstance()
						.getWeibo();
				TwitterApplication.mApi.setToken(accessToken.getToken(),
						accessToken.getTokenSecret());
				TwitterApplication.mApi.setUserId(user_id);
			}

			Intent intent = getIntent().getParcelableExtra(Intent.EXTRA_INTENT);

			intent = new Intent(OAuthActivity.this, TwitterActivity.class);
			this.finish();
			startActivity(intent);

		} catch (WeiboException e) {
			e.printStackTrace();
		}

	}

	public void saveUserWrapperToDB(AccessToken accessToken, String user_id) {
		dbHelper = new UserTokenTable(this);
		User user = getUserInfo(user_id);
		UserToken tokenWrapper = new UserToken();
		tokenWrapper.setToken(accessToken.getToken());
		tokenWrapper.setSecret(accessToken.getTokenSecret());
		tokenWrapper.setUser_id(user_id);
		tokenWrapper.setUserName(user.getScreenName());
		tokenWrapper.setIcon(getBytesFromImageURL(user.getProfileImageURL()));

		TwitterApplication.mPref = PreferenceManager
				.getDefaultSharedPreferences(this);
		SharedPreferences.Editor editor = TwitterApplication.mPref.edit();

		editor.putString(Preferences.USERNAME_KEY, tokenWrapper.getUserName());
		editor.putString(Preferences.ACCESSTOKEN, tokenWrapper.getToken());
		editor.putString(Preferences.ACCESSTOKEN_SECRET,
				tokenWrapper.getSecret());
		editor.putString(Preferences.CURRENT_USER_ID, tokenWrapper.getUser_id());
		editor.putLong(Preferences.LAST_DM_REFRESH_KEY, Utils.getNowTime());
		editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
				Utils.getNowTime());
		editor.commit();
		dbHelper.insert(tokenWrapper);
	}

	public User getUserInfo(String user_id) {
		Weibo weibo = OAuthConstant.getInstance().getWeibo();
		User user = null;
		weibo.setToken(OAuthConstant.getInstance().getToken(), OAuthConstant
				.getInstance().getTokenSecret());
		try {
			user = weibo.showUser(user_id);
		} catch (WeiboException e) {
			System.out.println(e);
		}

		return user;
	}

	public byte[] getBytesFromImageURL(URL myFileUrl) {

		Bitmap bitmap = null;
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		bitmap.compress(CompressFormat.JPEG, 85, outputStream);
		byte[] bytes = outputStream.toByteArray();

		return bytes;

	}
}
